<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 图书馆座位预约系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark navbar-custom">
        <div class="container-fluid">
            <a class="navbar-brand" href="/index.html">
                <i class="bi bi-book"></i> 图书馆座位预约
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/index.html">
                            <i class="bi bi-house"></i> 首页
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/booking.html">
                            <i class="bi bi-calendar-check"></i> 预约座位
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/my-bookings.html">
                            <i class="bi bi-list-check"></i> 我的预约
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/profile.html">
                            <i class="bi bi-person"></i> 个人中心
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" id="logoutBtn">
                            <i class="bi bi-box-arrow-right"></i> 退出
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-4 mb-4">
                <div class="card">
                    <div class="card-body text-center">
                        <i class="bi bi-person-circle" style="font-size: 5rem; color: #667eea;"></i>
                        <h4 class="mt-3" id="userName"></h4>
                        <p class="text-muted" id="studentNo"></p>
                        <div class="mt-3">
                            <span class="badge bg-primary" id="college"></span>
                            <span class="badge bg-info" id="major"></span>
                        </div>
                    </div>
                </div>

                <div class="card mt-3">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="bi bi-star-fill"></i> 信用分系统</h6>
                    </div>
                    <div class="card-body text-center">
                        <div class="credit-score mb-3" id="creditScore">100</div>
                        <div class="progress mb-3">
                            <div class="progress-bar" id="creditProgress" role="progressbar" style="width: 100%"></div>
                        </div>
                        <p class="small text-muted" id="creditLevel"></p>
                    </div>
                </div>

                <div class="card mt-3">
                    <div class="card-body">
                        <button class="btn btn-primary w-100 mb-2" data-bs-toggle="modal" data-bs-target="#passwordModal">
                            <i class="bi bi-key"></i> 修改密码
                        </button>
                    </div>
                </div>
            </div>

            <div class="col-md-8">
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-info-circle"></i> 个人信息</h5>
                    </div>
                    <div class="card-body">
                        <table class="table">
                            <tr>
                                <th width="30%">学号</th>
                                <td id="infoStudentNo"></td>
                            </tr>
                            <tr>
                                <th>姓名</th>
                                <td id="infoName"></td>
                            </tr>
                            <tr>
                                <th>性别</th>
                                <td id="infoGender"></td>
                            </tr>
                            <tr>
                                <th>学院</th>
                                <td id="infoCollege"></td>
                            </tr>
                            <tr>
                                <th>专业</th>
                                <td id="infoMajor"></td>
                            </tr>
                            <tr>
                                <th>联系电话</th>
                                <td id="infoPhone"></td>
                            </tr>
                        </table>
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-clock-history"></i> 信用分变动记录</h5>
                    </div>
                    <div class="card-body">
                        <div class="timeline" id="creditLogs"></div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-exclamation-triangle"></i> 违约记录</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>违约类型</th>
                                        <th>扣除分数</th>
                                        <th>违约时间</th>
                                        <th>申诉状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="violationList"></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="passwordModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">修改密码</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="passwordForm">
                        <div class="mb-3">
                            <label class="form-label">原密码</label>
                            <input type="password" class="form-control" id="oldPassword" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">新密码</label>
                            <input type="password" class="form-control" id="newPassword" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">确认新密码</label>
                            <input type="password" class="form-control" id="confirmPassword" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="changePassword()">确定</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="appealModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">违约申诉</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">申诉理由</label>
                        <textarea class="form-control" id="appealReason" rows="4" placeholder="请说明申诉理由"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitAppeal()">提交申诉</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://unpkg.com/layui@2.8.18/dist/layui.js"></script>
    <script src="/js/request.js"></script>
    <script>
        var layer;
        layui.use('layer', function(){
            layer = layui.layer;
        });
    </script>
    <script>
        let currentViolationId = null;
        let passwordModal = null;
        let appealModal = null;

        $(document).ready(function() {
            if (!request.checkLogin()) return;

            passwordModal = new bootstrap.Modal(document.getElementById('passwordModal'));
            appealModal = new bootstrap.Modal(document.getElementById('appealModal'));

            loadUserInfo();
            loadCreditLogs();
            loadViolations();

            $('#logoutBtn').click(function(e) {
                e.preventDefault();
                request.logout();
            });
        });

        function loadUserInfo() {
            request.get('/api/user/info').then(data => {
                $('#userName').text(data.name);
                $('#studentNo').text(data.studentNo);
                $('#college').text(data.college || '-');
                $('#major').text(data.major || '-');
                
                $('#infoStudentNo').text(data.studentNo);
                $('#infoName').text(data.name);
                $('#infoGender').text(data.gender === 1 ? '男' : '女');
                $('#infoCollege').text(data.college || '-');
                $('#infoMajor').text(data.major || '-');
                $('#infoPhone').text(data.phone || '-');

                const score = data.creditScore;
                $('#creditScore').text(score);
                $('#creditProgress').css('width', score + '%');
                
                const scoreClass = score >= 80 ? 'credit-high' : score >= 60 ? 'credit-medium' : 'credit-low';
                $('#creditScore').addClass(scoreClass);
                $('#creditProgress').addClass(score >= 80 ? 'bg-success' : score >= 60 ? 'bg-warning' : 'bg-danger');

                let level = '';
                if (score >= 80) {
                    level = '信用等级：优秀，无限制';
                } else if (score >= 60) {
                    level = '信用等级：良好，每天限制预约1次';
                } else if (score >= 40) {
                    level = '信用等级：一般，每天限制预约1次且不能预约热门座位';
                } else {
                    level = '信用等级：较差，禁止预约3天';
                }
                $('#creditLevel').text(level);
            });
        }

        function loadCreditLogs() {
            request.get('/api/user/credit-log').then(data => {
                if (data.length === 0) {
                    $('#creditLogs').html('<p class="text-muted text-center">暂无记录</p>');
                    return;
                }

                let html = '';
                data.slice(0, 10).forEach(log => {
                    const isAdd = log.changeScore > 0;
                    html += `
                        <div class="timeline-item">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <h6 class="mb-1">
                                        <span class="badge ${isAdd ? 'bg-success' : 'bg-danger'}">
                                            ${isAdd ? '+' : ''}${log.changeScore}
                                        </span>
                                        ${log.reason}
                                    </h6>
                                    <small class="text-muted">
                                        ${log.beforeScore} → ${log.afterScore}
                                    </small>
                                </div>
                                <small class="text-muted">${formatTime(log.createTime)}</small>
                            </div>
                        </div>
                    `;
                });
                $('#creditLogs').html(html);
            });
        }

        function loadViolations() {
            request.get('/api/user/violation').then(data => {
                if (data.length === 0) {
                    $('#violationList').html('<tr><td colspan="5" class="text-center text-muted">暂无违约记录</td></tr>');
                    return;
                }

                let html = '';
                data.forEach(v => {
                    const appealBadge = getAppealBadge(v.appealStatus);
                    html += `
                        <tr>
                            <td>${getViolationType(v.violationType)}</td>
                            <td><span class="text-danger">-${v.deductScore}</span></td>
                            <td>${formatTime(v.violationTime)}</td>
                            <td>${appealBadge}</td>
                            <td>
                                ${v.appealStatus ? '-' : `<button class="btn btn-sm btn-primary" onclick="showAppealModal(${v.id})">申诉</button>`}
                            </td>
                        </tr>
                    `;
                });
                $('#violationList').html(html);
            });
        }

        function getViolationType(type) {
            const map = {
                'NO_CHECKIN': '预约后未签到',
                'NO_CHECKOUT': '签到后未签退',
                'LEAVE_TIMEOUT': '临时离开超时'
            };
            return map[type] || type;
        }

        function getAppealBadge(status) {
            if (!status) return '<span class="badge bg-secondary">未申诉</span>';
            const map = {
                'PENDING': '<span class="badge bg-warning">待审核</span>',
                'APPROVED': '<span class="badge bg-success">已通过</span>',
                'REJECTED': '<span class="badge bg-danger">已拒绝</span>'
            };
            return map[status] || status;
        }

        function changePassword() {
            const oldPassword = $('#oldPassword').val();
            const newPassword = $('#newPassword').val();
            const confirmPassword = $('#confirmPassword').val();

            if (!oldPassword || !newPassword || !confirmPassword) {
                layer.msg('请填写完整', {icon: 2});
                return;
            }

            if (newPassword !== confirmPassword) {
                layer.msg('两次密码不一致', {icon: 2});
                return;
            }

            const loadIndex = layer.load(2);
            request.put('/api/user/password', {
                oldPassword: oldPassword,
                newPassword: newPassword
            }).then(() => {
                layer.close(loadIndex);
                passwordModal.hide();
                layer.msg('修改成功，请重新登录', {icon: 1});
                setTimeout(() => {
                    request.logout();
                }, 1500);
            }).catch(() => {
                layer.close(loadIndex);
            });
        }

        function showAppealModal(violationId) {
            currentViolationId = violationId;
            $('#appealReason').val('');
            appealModal.show();
        }

        function submitAppeal() {
            const reason = $('#appealReason').val().trim();
            if (!reason) {
                layer.msg('请填写申诉理由', {icon: 2});
                return;
            }

            const loadIndex = layer.load(2);
            request.post('/api/user/violation/appeal', {
                violationId: currentViolationId,
                reason: reason,
                images: null
            }).then(() => {
                layer.close(loadIndex);
                appealModal.hide();
                layer.msg('申诉已提交', {icon: 1});
                loadViolations();
            }).catch(() => {
                layer.close(loadIndex);
            });
        }

        function formatTime(time) {
            if (!time) return '-';
            return time.replace('T', ' ').substring(0, 16);
        }
    </script>
</body>
</html>

